define(['jquery','httpModule','mustache', 'api'], function($,httpModule,mustache, api) {
  var that = {};
  var $node ;

  var warnData = {
    '0': {
      text: '未分类',
      color: 'text-warning'
    },
    '1': {
      text: '信息',
      color: 'text-info'
    },
    '2': {
      text: '警告',
      color: 'text-warning'
    },
    '3': {
      text: '一般严重',
      color: 'js-list-golden'
    },
    '4': {
      text: '严重告警',
      color: 'js-list-orange'
    },
    '5': {
      text: '灾难告警',
      color: 'text-danger'
    }
  };

  var groupChange = function() {
    var hostGroupText = $(this).text();
    var groupId = $(this).attr('value');
    $('.groupText').text(hostGroupText);
    $('.host').children().remove();
    $('.hostText').text('请选择主机');
    $('.hostShow').show();
    $('.js-warn-list-table').children().remove();
    setTimeout(function() {
      getwarnTable(null, groupId);
    }, 200);

    setTimeout(function() {
      getHostList(groupId);
    }, 500);
  };

  var getwarnTable = function (hostId, groupId) {
    $.get('../template/warnTable.html')
    .then(function(ret) {
      var tableTpl = ret;
      var data = {};

      if (!!hostId) {
        data.hostids = hostId;
      } else {
        data.groupids = groupId;
      };

      // 获取数据
      httpModule.baseServ({
        url: api.getWarnList,
        dataType: 'jsonp',
        param: data
      })
      .then(function(data) {
        listData(tableTpl,data);
      })
    });
  };

  var getHostList = function (groupId) {
    $.get('../template/hostDrop.html')
    .then(function(ret) {
      var hostTpl = ret;

      // 获取数据
      httpModule.baseServ({
        url: api.getHostList,
        dataType: 'jsonp',
        param: {groupids: groupId}
      })
      .then(function(data) {
        hostData(hostTpl,data)
      },function(err){
        httpModule.baseServ(this)
        .then(function(data) {

          hostData(hostTpl,data)
        });
      });
    });
  };

  var getHostGroupList = function () {
    $.get('../template/groupDrop.html')
    .then(function(ret) {

      var groupTpl = ret;
      // 获取数据
      httpModule.baseServ({
        url: api.getHostGroupList,
        dataType: 'jsonp'
      })
      .then(function(data) {
        groupData(groupTpl,data)
      },function(err){

        httpModule.baseServ(this)
        .then(function(data) {
          groupData(groupTpl,data)
        });
      })
    });
  };

  //时间转换格式
  var format = function (timestamp){
    	var time = new Date(timestamp);
      Y = time.getFullYear() + '-';
      M = (time.getMonth()+1 < 10 ? '0'+(time.getMonth()+1) : time.getMonth()+1) + '-';
      D = (time.getDate() < 10 ? '0'+(time.getDate()) : time.getDate()) + ' ';
      h = (time.getHours() < 10 ? '0'+(time.getHours()) : time.getHours()) + ':';
      m = (time.getMinutes() < 10 ? '0'+(time.getMinutes()) : time.getMinutes());
      return Y+M+D+h+m;
  };

  //时间戳转天数
  var workingDate = function (timestamp){
    if (timestamp){
        var day = Math.floor(Math.abs(timestamp) / 1000 / 60 / 60 /24);
        //时间不足一个月
        if(day<30){
            return day+'天';
        }

        //时间不足一个月但不足一年
        if(day>=30 && day<=365){
            var year = parseInt(day%365/30)+'月零'+parseInt(day%365%30)+'天';
            if(parseInt(day%365%30) == 0){
            var year = parseInt(day%365/30)+'个月';
            return year;
            }
            return year;
        }

        //时间超过一年
        if(day>365 && parseInt(day%365/30)<12){
            var year = parseInt(day/365)+'年零'+parseInt(day%365/30)+'月';
            if(parseInt(day%365/30)==0){
            var year = parseInt(day/365)+'年';
            }
            return year;
        }
      }
    }

  //确认按钮
  var dealData = function() {
    var triggerid = JSON.parse($(this).attr('value'));
    var $tr = $(this).parent().parent();
		//得到当前的name
		var name = $tr.children('td').eq(1).children().text();
    console.log(name);

		//确定
		if(confirm('你确定处理 ' + name + ' 吗?')) {
      httpModule.baseServ({
        url: api.delWarnList,
        dataType: 'jsonp',
        param: {objectids: triggerid}
      })
      .then(function(ret) {
        alert('确认成功')
        $tr.remove();
      }, function(err) {
        alert('确认失败')
      });
    }
  };

  //listData
  var listData = function(tableTpl,data){
    data.result && data.result.map(function(item) {
      item.warnTypeColor = warnData[item.priority].color;
      item.priority = warnData[item.priority].text;
      var difftime  = new Date().getTime() - JSON.parse(item.lastchange) * 1000;
      //持续时间
      item.duration_time = workingDate(difftime);
      item.lastchange = format(JSON.parse(item.lastchange) * 1000);
      item.hosts = item.hosts[0].name;
    });

    var view = mustache.render(tableTpl, {
      list: data.result
    });
    $('.js-warn-list-table').append(view);
    $('tbody:first').delegate('.js-list-deal','click',dealData);
  }

  var groupData = function(groupTpl,data){
    var view = mustache.render(groupTpl, {
      list: data.result
    });
    $('.hostGroup').append(view);
  }

  var hostData = function(hostTpl,data){
    var view = mustache.render(hostTpl, {
      list: data.result
    });

    $('.host').append(view);
    $('.host li').on('click', function(){
      hostText = $(this).text();
      var hostId = $(this).attr('value');
      $('.hostText').text(hostText);
      $('.list-host-name').text(hostText);
      $('.js-warn-list-table').children().remove();
      getwarnTable(hostId);
    })
  }

  // 初始化获取dom
  var parseDOM = function(node) {
    $node = node;
  };

  // 绑定向外暴露的方法
  var bindListener = function() {
    that.getwarnTable = getwarnTable;
    that.getHostGroupList = getHostGroupList;
    that.getHostList = getHostList;
  };

  // 初始化时执行的函数
  var initPlugins = function() {
    $('.hostShow').hide();
    that.getwarnTable();

    setTimeout(function() {
      that.getHostGroupList()
    }, 500);

    $node.delegate('.hostGroup li', 'click', groupChange);
  };


  var init = function(node) {
    parseDOM(node);
    bindListener();
    initPlugins();
  };
  that.parseDOM = parseDOM;
  that.bindListener = bindListener;
  that.initPlugins = initPlugins;
  that.init = init;
  return that;
});
